package com.study.living.mediacodec;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CaptureScreenDataFile {

    private FileWriter fileWriter;
    private FileOutputStream fileOutputStream;

    private final char[] HEX_CHAR_TABLE = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    public CaptureScreenDataFile(Context context, String fileNamePrefix) {
        File cacheDir = context.getCacheDir();
        if (cacheDir.isDirectory()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd_HH:mm:ss");
            String time = sdf.format(new Date());
            String fileName = String.format(fileNamePrefix + "_%s_h265.txt", time);
            String fileName1 = String.format(fileNamePrefix + "_%s.h265", time);
            try {
                File file = new File(cacheDir.getAbsolutePath() + File.separator + fileName);
                File file1 = new File(cacheDir.getAbsolutePath() + File.separator + fileName1);
                fileOutputStream = new FileOutputStream(file1, true);
                fileWriter = new FileWriter(file, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void save(byte[] bytes){
        writeRawData(bytes);
        writeString(bytes);
    }

    private void writeRawData(byte[] bytes){
        if (fileOutputStream != null){
            try {
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void writeString(byte[] bytes) {
        if (fileWriter != null){
            StringBuilder sb = new StringBuilder();

            for (byte b : bytes) {
                sb.append(HEX_CHAR_TABLE[(b & 0xF0) >> 4]);
                sb.append(HEX_CHAR_TABLE[b & 0x0F]);
            }

            sb.append("\n");

            try {
                fileWriter.write(sb.toString());
                fileWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void closeFile() {
        if (fileWriter != null){
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileWriter = null;
        }

        if (fileOutputStream != null){
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileOutputStream = null;
        }
    }
}
